# -*- coding: utf-8 -*-

"""
 Create On: August 04, 2016
    Author: corvo
"""

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from sqlalchemy.orm import scoped_session, sessionmaker
from tornado.options import define, options
from Database.models import engine
from Handler.SubmitHandler import SubmitHandler
from Handler.QueryHandler import QueryHandler
from Handler.ModifyStateHandler import ModifyStateHandler
from Handler.QueryStateHandler import QueryStateHandler
from Handler.QueryByCardHandler import QueryByCardHandler
from Handler.DeleteRecordHandler import DeleteRecordHandler
from Handler.QueryCountHandler import QueryCountHandler

define("port", default=8080, help="run on the given port", type=int)


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/kuaidi/submit", SubmitHandler),
            (r"/kuaidi/queryAll", QueryHandler),
            (r"/kuaidi/modifyState", ModifyStateHandler),
            (r"/kuaidi/queryState", QueryStateHandler),
            (r"/kuaidi/queryByCard", QueryByCardHandler),
            (r"/kuaidi/deleteRecord", DeleteRecordHandler),
            (r"/kuaidi/queryCount", QueryCountHandler),
        ]
        tornado.web.Application.__init__(self, handlers)
        self.db = scoped_session(sessionmaker(bind=engine,
                                              autocommit=False, autoflush=True,
                                              expire_on_commit=False))
# session负责执行内存中的对象和数据库表之间的同步工作 
# Session类有很多参数,使用sessionmaker是为了简化这个过程
if __name__ == "__main__":
    tornado.options.parse_command_line()
    Application().listen(options.port)
    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        tornado.ioloop.IOLoop.instance().stop()

